import React, { useEffect, useRef, useState } from 'react';
import ProForm, { ModalForm, ProFormText, ProFormSelect, ProFormRadio } from '@ant-design/pro-form';
import { ProColumns, EditableProTable, ActionType } from '@ant-design/pro-table';
import { ExclamationCircleOutlined, RedoOutlined, PlusOutlined, MenuOutlined } from '@ant-design/icons';
import { Button, Divider, Input, FormInstance } from 'antd';
import { OptType } from '@/utils/constants';
import {
  getCategoryListByPage,
  getBrandListByPage,
  getGoodsDetail,
  doCreateCategory,
  doCreateBrand,
  checkGoodsIsExist,
  getSpell
} from '@/services/stock-goods/api';
import { isSupportSticky, isNull, showMsg, inArray } from '@/utils/utils';
import SpecTemplate from './SpecTemplate';
import { getDefaultTemplate } from '@/services/stock-goods/specTemplateApi';

const OptForm: React.FC<any> = (props) => {

  const { handleModalVisible, handleAdd, record = {}, optType = OptType.ADD } = props;

  const formRef = useRef<FormInstance>();
  const formRef2 = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const [brandOpen, setBrandOpen] = useState(false);
  // 当前选中的行编号，用于定位颜色
  const [clickRow, setClickRow] = useState('');
  // 当前编辑的行
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  // 品牌列表
  const [brandList, setBrandList] = useState<STOCKGOODSAPI.BrandItem[]>([]);
  const [brandName, setBrandName] = useState<string>('');
  const [brand, setBrand] = useState<string>('');
  // 品类列表
  const [categoryList, setCategoryList] = useState<STOCKGOODSAPI.CategoryItem[]>([]);
  const [className, setClassName] = useState<string>(''); // 输入框控制
  const [className1, setClassName1] = useState<string>(''); // 数据控制
  // 表格数据
  const [dataSource, setDataSource] = useState<STOCKGOODSAPI.GoodsSpecsItem[]>([]);
  const [list, setList] = useState<STOCKGOODSAPI.GoodsSpecsItem[]>([]);
  // 新增数量
  const [newAddNum, setNewAddNums] = useState<number>(0);
  // 删除数量
  const [deleteNum, setDeleteNum] = useState<number>(0);
  // 变更数量
  const [changeNum, setChangeNum] = useState<number>(0);

  const [beforeGoodsId, setBeforeGoodsId] = useState<string>('')
  // 规格模板
  const [specModalOpen, setSpecModalOpen] = useState<boolean>(false);
  const [specColumns, setSpecColumns] = useState<ProColumns<STOCKGOODSAPI.GoodsSpecsItem>[]>([]);

  const columns: ProColumns<STOCKGOODSAPI.GoodsSpecsItem>[] = [
    {
      title: '规格编号',
      dataIndex: 'specs_no',
      width: 60,
      editable: false,
    },
    ...specColumns,
    {
      title: '计量单位',
      dataIndex: 'unit',
      // width: 120,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项'
          }
        ]
      }
    },
    {
      title: '库存',
      dataIndex: 'inventory',
      valueType: 'digit',
      align: 'right',
      width: 90,
      editable: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项'
          }
        ]
      }
    },
    {
      title: '预警值',
      dataIndex: 'warn_inventory',
      valueType: 'digit',
      align: 'right',
      width: 70,
      fieldProps: {
        style: {
          width: '100%'
        }
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项'
          }
        ]
      }
    },
    {
      title: '销售价',
      dataIndex: 'selling_price',
      width: 90,
      valueType: 'money',
      align: 'right',
      fieldProps: {
        min: 0.01,
        precision: 2,
        style: {
          width: '100%'
        }
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项是必填项'
          }
        ]
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        A: '待添加',
        N: '正常',
        D: '作废'
      },
      width: 60,
      editable: false,
      // formItemProps: {
      //   rules: [
      //     {
      //       required: true,
      //       message: '此项是必填项'
      //     }
      //   ]
      // }
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : false,
      width: 130,
      render: (text, entity: STOCKGOODSAPI.GoodsSpecsItem, idx, action) => {
        const btnlist = [
          <a key="edit" onClick={() => action?.startEditable?.(entity.id as string)}>编辑</a>
        ];
        if (isNull(entity.specs_id)) {
          btnlist.push(
            <a key="delete"
              onClick={() => {
                if (entity.create_user_id) {
                  setDeleteNum(deleteNum + 1);
                }
                // console.info(JSON.parse(JSON.stringify(dataSource)));
                const recombineList = dataSource.filter(({ id }) => { console.info(id); return id !== entity.id }).map((item, index) => ({
                  ...item,
                  // specs_no: index < 10 ? `00${index + 1}` : `0${index + 1}`,
                }));
                // console.info(entity.id, recombineList);
                setDataSource(recombineList);
              }}
            >
              删除
            </a>
          );
        } else if (entity.update) {
          btnlist.push(
            <a key="update"
              onClick={() => {
                // console.log('aaaa', record1, _)
                const yuan = list.find(item => item.id === entity.id);
                dataSource[idx] = yuan;
                dataSource[idx].update = false;
                setDataSource(Object.assign([], dataSource));
              }}
            >
              恢复
            </a>
          );
        } else {
          btnlist.push(
            <a key="update"
              onClick={() => {
                // console.log('aaaabbb', record1.status, _)
                const status = entity.status === 'N' ? 'D' : 'N';
                dataSource[idx].status = status;
                dataSource[idx].update = true;
                setDataSource(Object.assign([], dataSource));
              }}
            >
              {entity.status === 'N' ? '作废' : '启用'}
            </a>
          );
        }
        btnlist.push(
          <a key="copy"
            onClick={() => {
              action?.addEditRecord({
                specs_name: entity.specs_name,
                warn_inventory: entity.warn_inventory,
                selling_price: entity.selling_price,
                unit: entity.unit,
                specs_id: '',
                // specs_no: `${(record.specs_num || 0) + 1 + dataSource.length}`.padStart(3, '0'),
                specs_no: `${1 + dataSource.length}`.padStart(3, '0'),
                id: `new_${Date.now()}`,
                inventory: 0,
                status: 'A',
                template_value: { ...entity.template_value },
                ...entity.template_value
              })
            }}>
            复制
          </a>
        );
        return btnlist;
      }
    }
  ];

  // 复原
  const onRestore = () => {
    setNewAddNums(0);
    setDeleteNum(0);
    setChangeNum(0);
    if (optType === OptType.ADD) {
      setDataSource([]);
    } else {
      // setDataSource(Object.assign([], list));
      setDataSource(JSON.parse(JSON.stringify(list)));
    }
    if (editableKeys.length > 0) {
      actionRef.current?.cancelEditable?.(editableKeys[0]);
    }
  }

  const onAddInputChange = (event: any, type: string) => {
    event.preventDefault();
    event.stopPropagation();
    if (type === 'className') {
      setClassName(event.target.value);
    } else {
      setBrandName(event.target.value);
    }
  };

  // 新增分类
  const addClass = async () => {
    if (!className) {
      return;
    }
    setClassName1(className);
    try {
      const data: STOCKGOODSAPI.CategoryItem = await doCreateCategory({ class_name: className });
      setCategoryList([...categoryList, { ...data }]);
      setClassName('');
      formRef2.current?.setFieldsValue({
        class_id: data.class_id
      })
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  const onClassPressEnter = async (e: any) => {
    e.preventDefault();
    const value = e.target.value
    if (!value) {
      return
    }
    setClassName1(value);
    try {
      const data: STOCKGOODSAPI.CategoryItem = await doCreateCategory({ class_name: className });
      const list = Object.assign([], categoryList);
      list.push(data);
      setCategoryList(list);
      setClassName('');
      setClassName1(className);
      formRef2.current?.setFieldsValue({
        class_id: data.class_id
      })
    } catch (error) {
      // console.log(error);
      showMsg(error?.data?.errmsg);
    }
  }

  // 新增品牌
  const addBrand = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    setBrandOpen(false);
    if (!brandName) {
      return;
    }
    setBrand(brandName);
    try {
      const data: STOCKGOODSAPI.BrandItem = await doCreateBrand({ brand_name: brandName });

      const good = formRef2.current?.getFieldValue('goods_name');
      // console.log('data', data, good, brandList);
      if (good && good.trim()) {
        const { py } = await getSpell(brandName + good)
        formRef2.current?.setFieldsValue({
          goods_py: py
        })
      }
      setBrandList([...brandList, { ...data }]);
      // setBrand(brandName);
      setBrandName('');
      formRef2.current?.setFieldsValue({
        brand_id: data.brand_id
      })
    } catch (error) {
      // console.log('error', error)
      showMsg(error?.data?.errmsg);
    }
  }

  const onBrandPressEnter = async (e: any) => {
    e.preventDefault();
    e.stopPropagation();
    const value = e.target.value
    if (!value) {
      return
    }
    setBrand(value);
    setBrandOpen(false)
    try {
      const data: STOCKGOODSAPI.BrandItem = await doCreateBrand({ brand_name: brandName });
      const good = formRef2.current?.getFieldValue('goods_name');
      if (good && good.trim()) {
        const { py } = await getSpell(brandName + good)
        formRef2.current?.setFieldsValue({
          goods_py: py,
        })
      }
      const list = Object.assign([], brandList);
      list.push(data);
      setBrandList(list);
      setBrandName('');
      formRef2.current?.setFieldsValue({
        brand_id: data.brand_id
      })
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  const preventDefault = (e: any) => {
    e.preventDefault();
  }

  useEffect(() => {
    if (record.goods_id) {
      getGoodsDetail(record.goods_id).then((data: STOCKGOODSAPI.GoodsItem) => {
        let historyData = false;
        // 套用规格模板回显
        const template_content = data.template_content ?? [];
        applySpecTemplate({ template_conent: template_content }, true);
        const list = data.goods_specs_list?.map(item => {
          const tmpItem = (({ specs_id, specs_name, inventory, selling_price, specs_no, status, unit, warn_inventory, template_value }) => ({
            id: specs_id, specs_id, specs_name, inventory, selling_price, specs_no, status, unit, warn_inventory, template_value
          }))(item);
          const specTempValue = item.template_value ?? {};
          template_content.forEach(specN => {
            tmpItem[specN] = specTempValue[specN];
            if (!tmpItem[specN] && historyData) {
              tmpItem[specN] = item.specs_name;
            }
          });
          return tmpItem;
        });
        // const listSort = list?.sort((a, b) => {
        //   return a.specs_no - b.specs_no
        // })

        setDataSource(JSON.parse(JSON.stringify(list || [])));
        setList(JSON.parse(JSON.stringify(list || [])));
      });
      setBeforeGoodsId(record.goods_id);
    } else {
      // 默认的规格模板
      getDefaultTemplate().then(res => {
        applySpecTemplate(res, true);
      });
    }
  }, [record]);

  useEffect(() => {
    Promise.all([getCategoryListByPage({ current: 1, pageSize: 10000 }), getBrandListByPage({ current: 1, pageSize: 10000 })]).then(([data, data2]) => {
      // @ts-ignore
      setCategoryList(data.record_list || []);
      // @ts-ignore
      setBrandList(data2.record_list || []);

      formRef2.current?.setFieldsValue({
        class_id: record.class_id,
        brand_id: record.brand_id
      })
    })
    // document.querySelector('.modal-form')?.addEventListener('keypress', (e: any) => {
    //   if (e.keyCode === 13) {
    //     preventDefault(e);
    //   }
    // })
  }, []);

  // 查询商品是否有改动
  const checkChange = (rowKey: any, data: any) => {
    let newCount = 0, updateCount = 0;
    const ids = [];
    const checkList = Object.assign([], dataSource);
    // 新增的商品
    if (rowKey.includes('new')) {
      checkList.push(data);
    } else {
      checkList[data.index] = data;
    }
    // console.log('checkList', checkList);
    checkList.forEach((element, key) => {
      // 新增的
      if ((element.id).includes('new')) {
        newCount += 1;
      } else { // 原数组里变更的
        // 原数组的换了
        // eslint-disable-next-line no-lonely-if
        let ary = list.filter(item => item.id === element.id);
        ary = isNull(ary) ? {} : ary[0];
        // console.log('aaa', element.warn_inventory, ary.warn_inventory)
        if (element.specs_name !== ary.specs_name || element.unit !== ary.unit ||
          element.warn_inventory !== ary.warn_inventory || element.total_inventory !== ary.total_inventory ||
          element.selling_price !== ary.selling_price) {
          updateCount += 1;
          // console.log('bbb')
          element.update = true;
        }
      }
      ids.push(element.id);
    });
    setDataSource(Object.assign([], checkList));
    setNewAddNums(newCount);
    setChangeNum(updateCount);
  }

  const renderClass = () => {
    const list1 = [];
    categoryList.map(item => {
      list1.push({
        label: `${item.class_name}（${item.class_py}）`,
        value: item.class_id as string,
        class_name: item.class_name,
      })
    })
    if (!isNull(record.class_id) && !inArray(categoryList, record.class_id, 'bol', 'class_id')) {
      list1.push({
        label: `${record.class_name}`,
        value: record.class_id,
        disabled: true,
      })
    }
    return list1;
  }

  const renderBrand = () => {
    const list1 = [];
    brandList.map(item => {
      list1.push({
        label: `${item.brand_name}（${item.brand_py}）`,
        value: item.brand_id,
        data: item,
      })
    })
    if (!isNull(record.brand_id) && !inArray(brandList, record.brand_id, 'bol', 'brand_id')) {
      list1.push({
        label: `${record.brand_name}`,
        value: record.brand_id,
        disabled: true,
      })
    }
    return list1;
  }

  /**
   * 应用规格模板
   * @param value
   */
  const applySpecTemplate = (value: Pick<STOCKGOODSAPI.SpecTemplate, 'template_conent'>, init = false) => {
    const specArr = value.template_conent.map(elem => (
      { title: elem, dataIndex: elem, formItemProps: { rules: [{ required: true, message: elem + '是必填项' }] }, isSpec: true }
    ));
    setSpecColumns(specArr);
    if (!init)
      setEditableRowKeys(dataSource.map(({ id }) => id as string));
  };

  return <ModalForm
    className="modal-form"
    width="80%"
    title="新增/编辑商品"
    layout="horizontal"
    visible
    formRef={formRef2}
    modalProps={{
      maskClosable: false,
      bodyStyle: { maxHeight: 'calc(94vh - 74px)', overflowY: 'auto' }
    }}
    onClick={() => setBrandOpen(false)}
    onVisibleChange={handleModalVisible}
    onFinish={async (value) => {
      if (!dataSource.length) {
        showMsg('商品规格不能为空');
        return;
      }
      if (editableKeys.length > 0) {
        showMsg('请先保存正在编辑的规格信息');
        return;
      }
      // 规格模板规格列表
      const template_content = columns.filter(({ isSpec }: any) => isSpec).map(elem => elem.dataIndex as string) || [];
      if (template_content.length === 0) {
        showMsg('请选择一个规格模板');
        return;
      }
      const goods_specs_list: STOCKGOODSAPI.GoodsSpecsItem[] = dataSource.map(({ ...specObj }) => {
        const template_value = {};
        template_content.forEach(spec => {
          template_value[spec] = specObj[spec];
          delete specObj[spec];
        });
        specObj.template_value = template_value;
        if (specObj.status === 'A') {
          specObj.status = 'N';
        }
        return specObj;
      });
      // const class_name = categoryList.find(item => item.class_id === value.class_id.split('|')[0])?.class_name;
      value = Object.assign({}, value, { class_name: className1 || record.class_name, brand_name: brand || record.brand_name, template_content, goods_specs_list });
      // console.info('-------: ', value);

      const success = await handleAdd(value);
      if (success) {
        handleModalVisible(false);
      }
    }}
    submitter={{
      searchConfig: {
        resetText: '取消',
        submitText: '确定'
      }
    }}>
    <ProForm.Group>
      <ProFormSelect
        rules={
          [
            {
              required: true,
              message: '请输入或选择分类'
            }
          ]
        }
        label="商品分类"
        placeholder="请输入或选择分类"
        width="md"
        name="class_id"
        options={renderClass()}
        fieldProps={{
          optionFilterProp: 'children',
          filterOption: (input, option) => {
            return (option?.label?.toLowerCase()).includes(input.toLowerCase())
          },
          dropdownRender: (menu) => {
            return <div>
              {menu}
              <Divider style={{ margin: '4px 0' }} />
              <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', padding: 8 }}>
                <Input
                  style={{ flex: 'auto', height: 24 }}
                  value={className}
                  onPressEnter={onClassPressEnter}
                  onChange={(event) => onAddInputChange(event, 'className')} />
                <a style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer' }} onClick={addClass}>
                  <PlusOutlined /> 新增分类
                </a>
              </div>
            </div>
          },
          onSelect: async (val, opt) => {
            // console.log('opt', val, opt)
            const value = opt.class_name;
            setClassName('');
            setClassName1(value);
          },
          showSearch: true
        }}
      />
      <ProFormSelect
        rules={
          [
            {
              required: true,
              message: '请输入或选择品牌'
            }
          ]
        }
        label="商品品牌"
        placeholder="请输入或选择品牌"
        width="md"
        name="brand_id"
        options={renderBrand()}
        fieldProps={{
          // onFocus: () => setBrandOpen(true),
          onClick: (e) => {
            e.preventDefault(); e.stopPropagation();
            setBrandOpen(!brandOpen)
          },
          open: brandOpen,
          optionFilterProp: 'children',
          filterOption: (input, option) => {
            return (option.label.toLowerCase()).includes(input.toLowerCase())
          },
          dropdownRender: (menu) => {
            return <div>
              {menu}
              <Divider style={{ margin: '4px 0' }} />
              <div style={{ display: 'flex', alignItems: 'center', flexWrap: 'nowrap', padding: 8 }}>
                <Input
                  style={{ flex: 'auto', height: 24 }}
                  value={brandName}
                  onPressEnter={onBrandPressEnter}
                  onClick={event => { event.preventDefault(); event.stopPropagation(); }}
                  onChange={(event) => onAddInputChange(event, 'brandName')} />
                <a style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer', fontSize: 12 }}
                  onClick={addBrand}>
                  <PlusOutlined /> 新增品牌
                </a>
              </div>
            </div>
          },
          onSelect: async (val, opt) => {
            const value = opt.data.brand_name;
            setBrandName('');
            setBrand(value);
            setBrandOpen(false);
            const good = formRef2.current?.getFieldValue('goods_name');
            if (good && good.trim()) {
              const { py } = await getSpell(value + good)
              formRef2.current?.setFieldsValue({
                goods_py: py
              })
            }
          },
          showSearch: true,
          filterOption: false
        }}
      />

    </ProForm.Group>

    <ProForm.Group>
      <ProFormText
        rules={
          [
            {
              required: true,
              message: '请输入商品编码'
            },
            {
              validator: async (rule, value) => {
                if (!value || value && !value.trim()) {
                  return Promise.reject();
                }
                if (optType === OptType.ADD || optType === OptType.EDIT && beforeGoodsId !== value) {
                  const { is_exist } = await checkGoodsIsExist({
                    goods_id: value
                  });
                  if (is_exist === '1') {
                    return Promise.reject("商品编码已存在");
                  }
                  return Promise.resolve();
                }
                return Promise.resolve();
              }
            }
          ]
        }
        validateTrigger="onBlur"
        label="商品编码"
        placeholder="请输入商品编码"
        width="md"
        initialValue={record.goods_id}
        name="goods_id"
        readonly={record.goods_id}
        fieldProps={{
          onPressEnter: preventDefault
        }}
      />
    </ProForm.Group>

    <ProForm.Group>
      <ProFormText
        rules={
          [
            {
              required: true,
              message: '请输入商品名称'
            },
          ]
        }
        label="商品名称"
        placeholder="请输入商品名称"
        width="md"
        name="goods_name"
        initialValue={record.goods_name}
        fieldProps={{
          onPressEnter: preventDefault,
          onBlur: async (val) => {
            const value = val.target.value;
            // console.log('brandName', brand)
            if (value && value.trim()) {
              const { py } = await getSpell(brand + value)
              formRef2.current?.setFieldsValue({
                goods_py: py
              })
            }
          }
        }}
      />
      <ProFormText
        rules={
          [
            {
              required: true,
              message: '请输入商品检索码'
            }
          ]
        }
        label="商品检索码"
        placeholder="请输入商品检索码"
        width="md"
        // validateTrigger="onBlur"
        name="goods_py"
        initialValue={record.goods_py}
        fieldProps={{
          onPressEnter: preventDefault
        }}
      />
    </ProForm.Group>

    <ProForm.Group>
      <ProFormRadio.Group
        rules={
          [
            {
              required: true
            }
          ]
        }
        name="scope"
        width="md"
        label="供应范围"
        initialValue={record.scope || 'B'}
        options={[
          {
            label: '本科室',
            value: 'B'
          },
          {
            label: '全院',
            value: 'A'
          }
        ]}
      />

      <ProFormRadio.Group
        rules={
          [
            {
              required: true
            }
          ]
        }
        name="goods_status"
        label="商品状态"
        width="md"
        initialValue={record.goods_status || 'O'}
        options={[
          {
            label: '上架',
            value: 'O'
          },
          {
            label: '下架',
            value: 'D'
          }
        ]}
      />
    </ProForm.Group>

    <EditableProTable<STOCKGOODSAPI.GoodsSpecsItem>
      rowKey="id"
      headerTitle={'商品规格'}
      // cardBordered
      scroll={{ y: 'calc(94vh - 78px - 314px)' }}
      className={'update-goods-table'}
      actionRef={actionRef}
      formRef={formRef}
      bordered
      rowClassName={(data: STOCKGOODSAPI.GoodsItem) => {
        if (data.id === clickRow) {
          return 'tableRowClick';
        }
        if (!isNull(record.goods_id) && (data.id).includes('new')) {
          return 'new-add';
        }
        if (!isNull(record.goods_id) && data.update) {
          return 'update-bg';
        }
        return '';
      }}
      onRow={record => {
        return {
          onClick: event => { setClickRow(record.id) }, // 点击行
          onMouseEnter: event => { }, // 鼠标移入行
          onMouseLeave: event => { },
        };
      }}
      value={dataSource}
      onChange={value => {
        setDataSource(Object.assign([], value));
      }}
      toolbar={
        optType === OptType.EDIT ?
          {
            menu: {
              type: 'inline',
              items: [
                {
                  key: 'restore',
                  label: <Button className='btnColor2' style={{ marginLeft: 10 }} onClick={onRestore} type="primary" icon={<RedoOutlined />}>变更复原</Button>
                }
              ]
            }
          } : undefined
      }
      recordCreatorProps={{
        // newRecordType: 'dataSource',
        record: () => ({
          id: `new_${Date.now()}`,
          // specs_no: record.specs_num ? `${record.specs_num + 1 + newAddNum}`.padStart(3, '0') : dataSource.length < 10 ? `00${dataSource.length + 1}` : `0${dataSource.length + 1}`,
          // specs_no: `${(record.specs_num || 0) + 1 + dataSource.length}`.padStart(3, '0'),
          specs_no: `${1 + dataSource.length}`.padStart(3, '0'),
          status: 'A',
          inventory: 0,
        }),
        // 点击添加行的时候，滚动条定位到最新一条记录
        onClick: () => {
          // 获得滚动条区域
          const bodyObj = document.getElementsByClassName('update-goods-table')[0].getElementsByClassName('ant-table-body')[0];
          try {
            // 获得每一行的高度
            const lineHeight = bodyObj.getElementsByClassName('ant-table-row')[0].clientHeight;
            setTimeout(() => {
              bodyObj.scrollTop = bodyObj.scrollHeight + lineHeight;
            }, 10);
          } catch (error) {

          }
        }
      }}
      editable={{
        type: 'single',
        editableKeys,
        onChange: setEditableRowKeys,
        onlyOneLineEditorAlertMessage: '请先保存正在编辑的规格信息',
        onlyAddOneLineAlertMessage: '请先保存正在编辑的规格信息',
        actionRender: (row, config, defaultDom) => [defaultDom.save, defaultDom.cancel],
        onSave: async (rowKey, data) => {
          checkChange(rowKey, data);
          if (editableKeys.length > 1) {
            setEditableRowKeys(editableKeys.filter(key => key !== rowKey));
          }
        }
      }}
      toolBarRender={() => [
        <>
          {optType === OptType.EDIT && <div>
            <span>新增：</span>
            <span style={{ color: '#52C41A' }}>{newAddNum}</span>
            <span style={{ paddingLeft: '20px' }}>删除：</span>
            <span style={{ color: '#333' }}>{deleteNum}</span>
            <span style={{ paddingLeft: '20px' }}>变更：</span>
            <span style={{ color: '#FAAD15' }}>{changeNum}</span>
          </div>}
          <Button style={{ marginLeft: 10 }} onClick={() => { setSpecModalOpen(true) }} type="primary" icon={<MenuOutlined />}>规格模板</Button>
        </>
      ]}
      columns={columns}
    />

    <div className="modal-tips">
      <ExclamationCircleOutlined />
      <span>编辑商品和新增商品规格信息后，请点击下方<strong>确定</strong>按钮保存结果</span>
    </div>

    <SpecTemplate open={specModalOpen} onOpenChange={setSpecModalOpen} onSelected={applySpecTemplate} />
  </ModalForm>
}
export default OptForm;
